package com.dd.seckill.cluster.config.redis.ratelimit;

import com.dd.seckill.cluster.config.exception.BusinessException;
import com.dd.seckill.cluster.pojo.annotation.RateLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Author liuxianmeng
 * @CreateTime 2025/9/14 9:24
 * @Description 限流切面实现
 */
@Aspect
@Component
public class RateLimitAspect {

    @Autowired
    private RedisRateLimiter rateLimiter;

    @Around("@annotation(rateLimit)")
    public Object around(ProceedingJoinPoint joinPoint, RateLimit rateLimit) throws Throwable {
        String key = rateLimit.key();
        if (key.isEmpty()) {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            key = signature.getMethod().getName();
        }

        if (!rateLimiter.tryAcquire(key, rateLimit.limit(), rateLimit.window())) {
            throw new BusinessException(410001, rateLimit.message());
        }

        return joinPoint.proceed();
    }
}